package com.winning.dps.rda.common.Exception;

import com.winning.dps.rda.common.util.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.servlet.NoHandlerFoundException;


/**
 * 全局请求异常处理器
 **/ 
@RestControllerAdvice
public class BaseExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(BaseException.class)
	public ResponseEntity handleException(BaseException e){
		ResponseEntity re = new ResponseEntity();
		re.put("code", e.getCode());
		re.put("msg", e.getMessage());
        logger.error("BaseException:errorCode="+e.getCode()+"errorMsg="+e.getMessage());
		return re;
	}

	@ExceptionHandler(BindException.class)
	public ResponseEntity bindExceptionHandler(BindException ex){
		ResponseEntity re = new ResponseEntity();
		re.put("code", "400");
		re.put("msg", ex.getMessage());
        logger.error("BindException:errorCode=" + 400 + "errorMsg=" + ex.getMessage());
        return re;
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public ResponseEntity handlerNoFoundException(Exception e) {
		logger.error(e.getMessage(), e);
        return ResponseEntity.error(404, "路径不存在，请检查路径是否正确");
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public ResponseEntity handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return ResponseEntity.error("数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public ResponseEntity handleAuthorizationException(AuthorizationException e){
		logger.error(e.getMessage(), e);
        return ResponseEntity.error("没有权限，请联系管理员授权");
	}

	@ExceptionHandler(Exception.class)
	public ResponseEntity handleException(Exception e){
		logger.error(e.getMessage(), e);
		return ResponseEntity.error();
	}



}
